package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Contract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Map;

/**
 * 预约信息Service业务层处理
 *
 * @author zhutao
 * @date 2025-01-03
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询预约信息
     *
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id) {
        return getById(id);
    }

    /**
     * 查询预约信息列表
     *
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation) {
        // 设置预约状态为待报道
        reservation.setStatus(0);
        // 获取当前登录用户的id
        String userId = UserThreadLocal.getUserId().toString();
        // 设置创建人
        reservation.setCreateBy(userId);
        // 获取当前预约时间
        LocalDateTime ldt = LocalDateTimeUtil.of(reservation.getTime());
        // 查询该用户在该时间段内预约的数量
        Integer count = reservationMapper.CountByTime(ldt, userId);
        if (count > 0) {
            throw new RuntimeException("此手机号在该时间段内预约了" + count + "次，请选择其他时间段");
        }
        return save(reservation) ? 1 : 0;
    }

    /**
     * 修改预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation) {
        return updateById(reservation) ? 1 : 0;
    }

    /**
     * 批量删除预约信息
     *
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除预约信息信息
     *
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public Integer getCancelledReservationCount() {
        //获取当天开始时间与结束时间
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        //获取当前登录用户的id
        String userId = UserThreadLocal.getUserId().toString();
        //查询当前用户当天取消的预约数量
        Integer count = reservationMapper.getCancelledReservationCount(startTime, endTime, userId);
        return count;
    }

    @Override
    public List<Map<String, Integer>> getCountByTime(Long time) {
        //将time转化为LocalDateTime，并准备查询时间
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        //查询时间段内预约数量
        List<Map<String, Integer>> countByTime = reservationMapper.getCountByTime(startTime, endTime);
        return countByTime;
    }

    @Override
    public List<Reservation> selectReservationPage(Reservation reservation) {
        //获取当前登录用户的id
        String userId = UserThreadLocal.getUserId().toString();
        //查询状态为0的预约信息
        return lambdaQuery().eq(Reservation::getCreateBy, userId).list();
    }

    @Override
    public void changeStatus(Long id) {
        //获取当前登录用户的id
        String userId = UserThreadLocal.getUserId().toString();
        //获取当前时间
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        //使用MP更改update_by,userId的数据为预约状态为取消
        lambdaUpdate()
                .eq(Reservation::getId, id)
                .eq(Reservation::getCreateBy, userId)
                .set(Reservation::getStatus, 2)
                .set(Reservation::getUpdateBy, userId)
                .set(Reservation::getUpdateTime, ldt)
                .update();
    }

    @Override
    public void updateReservationStatusJob() {
        //查询状态为0的预约信息
        List<Reservation> list = lambdaQuery().eq(Reservation::getStatus, 0).list();
        //获取当前时间
        long time = System.currentTimeMillis();
        //构造更新对象集合
        List<Reservation> updateContractList = new ArrayList<>();
        //判断预约时间是否超时一个小时与当前时间，小于则更改预约状态为已过期
        list.forEach(reservation -> {
            LocalDateTime ldt = LocalDateTimeUtil.of(reservation.getTime());
            //得到一个小时后的时间
            LocalDateTime endTime = ldt.plusHours(1);
            //判断是否超时
            if (endTime.isAfter(LocalDateTimeUtil.of(time))) {
                updateContractList.add(buildUpdateReservation(reservation, 3));
            }
        });
        //批量更新
        updateBatchById(updateContractList);
    }

    private Reservation buildUpdateReservation(Reservation reservation, Integer status) {
        Reservation updateReservation = new Reservation();
        updateReservation.setId(reservation.getId());
        updateReservation.setStatus(status);
        return updateReservation;
    }
}
